package com.jw.config;

import java.util.List;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.aliyuncs.alidns.model.v20150109.DescribeDomainRecordsResponse.Record;
import com.jw.common.DnsConstant;
import com.jw.util.AliYunUtil;
import com.jw.util.IpUtil;
import com.jw.util.RedisUtil;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;

@Component
public class DnsTask {
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Value("${server.port}")
	private String port;
	@Value("${tplink_dns}")
	private String tplinkDns;
	@Value("${domain_name}")
	private String domainName;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private AliYunUtil aliYunUtil;

	@Scheduled(cron = "0 0/1 * * * *")
	public void work() {
		String redisIp = redisUtil.get("ip");
		String publicIp = getIpCanUse();
		logger.info("redisIp:" + redisIp + "||公共ip:" + publicIp);
		if (Objects.equals(publicIp, redisIp)) {
			logger.info("ip没有变化");
			return;
		} else {
			if (publicIp == null) {
				logger.error("公共ip获取出现异常");
				return;
			}
			// 两边获取的ip不同有可能只是没有连接到redis,所以更新前再查询阿里云确认一遍
			boolean ipExist = aliYunUtil.checkDomainRecord(domainName, publicIp, "@", "A");
			if (ipExist) {
				return;
			}
			// 更新redis保存的ip
			redisUtil.set("ip", publicIp);
			// 更新所有解析的域名
			List<Record> list = aliYunUtil.getDomainRecords(domainName);
			logger.info("------------准备更新解析记录-------------\n");
			for (Record record : list) {
				if (!Objects.equals("TXT", record.getType())) {
					record.setValue(publicIp);
					aliYunUtil.updateATypeDomainRecord(record.getRecordId(), publicIp, record.getRR());
					logger.info(JSONUtil.toJsonStr(record));
				}
			}
		}
	}

	/**
	 * 检测拿到的ip地址是否可以使用
	 * 
	 * @param ip
	 * @return
	 */
	private boolean checkIp(String ip) {
		try {
			String r = HttpUtil.get("http://" + ip + ":" + port + "/test", 3000);
			if ("success".equals(r)) {
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 查找可以使用的ip
	 * 
	 * @return
	 */
	public String getIpCanUse() {
		// 通过tplink的自带域名查找ip
		String ip = IpUtil.getIpByDomain(tplinkDns);
		if (checkIp(ip)) {
			return ip;
		} else {
			// 通过ipip.net查找公共ip
			ip = IpUtil.getIP(DnsConstant.ipip_url, DnsConstant.ipcn_reg);
			if (checkIp(ip)) {
				return ip;
			} else {
				// 通过t086网站查找公共ip
				ip = IpUtil.getIP(DnsConstant.t086_url, DnsConstant.t086_reg);
				if (checkIp(ip)) {
					return ip;
				} else {
					// 通过ip.cn网站查找公共域名
					ip = IpUtil.getIP(DnsConstant.ipcn_url, DnsConstant.ipcn_reg);
					if (checkIp(ip)) {
						return ip;
					} else {
						return null;
					}
				}
			}
		}
	}
}
